package cn.schoolwow.quickdao.module.database.dml.json.flow.common;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.module.database.dml.common.domain.ManipulationOption;
import cn.schoolwow.quickdao.module.database.parent.flow.executor.ExecuteUpdateConnectionFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import com.alibaba.fastjson.JSONArray;

import java.util.ArrayList;
import java.util.List;

public class DeleteBySingleUniqueFieldFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        setSingleUniqueFieldName(flowContext);
        setStatement(flowContext);
        setParameters(flowContext);
        executeStatement(flowContext);
    }

    @Override
    public String name() {
        return "根据单个唯一字段删除JSONArray";
    }

    private void setSingleUniqueFieldName(FlowContext flowContext){
        ManipulationOption manipulationOption = flowContext.checkInstanceData(ManipulationOption.class);

        String singleUniqueFieldName = manipulationOption.uniqueFieldNames.iterator().next();
        flowContext.putCurrentFlowData("singleUniqueFieldName", singleUniqueFieldName);
    }

    private void setStatement(FlowContext flowContext) {
        String singleUniqueFieldName = flowContext.checkData("singleUniqueFieldName", String.class);
        String tableName = flowContext.checkData("tableName", String.class);
        JSONArray instances = flowContext.checkData("instances", JSONArray.class);
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);

        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("delete from " + quickDAOConfig.databaseContext.databaseProvider.escape(tableName) + " where " + quickDAOConfig.databaseContext.databaseProvider.escape(singleUniqueFieldName) + " in (");
        for(int i=0;i<instances.size();i++){
            sqlBuilder.append("?,");
        }
        sqlBuilder.deleteCharAt(sqlBuilder.length() - 1);
        sqlBuilder.append(")");
        flowContext.putData("sql", sqlBuilder.toString());
    }

    public void setParameters(FlowContext flowContext) {
        String singleUniqueFieldName = (String) flowContext.checkData("singleUniqueFieldName");
        JSONArray instances = (JSONArray) flowContext.checkData("instances");

        List<Object> parameters = new ArrayList();
        for(int i=0;i<instances.size();i++){
            Object value = instances.getJSONObject(i).get(singleUniqueFieldName);
            parameters.add(value);
        }
        flowContext.putTemporaryData("parameters", parameters);
    }

    private void executeStatement(FlowContext flowContext) {
        flowContext.startFlow(new ExecuteUpdateConnectionFlow())
                .putTemporaryData("name", "根据单个唯一字段删除JSONArray")
                .execute();
    }
}
